class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def addOneRow(self, root, val, depth):
        """
        :type root: TreeNode
        :type val: int
        :type depth: int
        :rtype: TreeNode
        """
        depth = depth - 1
        if not depth:
            return TreeNode(val, root)

        def search(node, val, now):
            if now == depth:
                left_node = node.left
                right_node = node.right
                node.left = TreeNode(val, left=left_node)
                node.right = TreeNode(val, left=None, right=right_node)
            else:
                if node.left:
                    node.left = search(node.left, val, now + 1)
                if node.right:
                    node.right = search(node.right, val, now + 1)
            return node

        return search(root, val, 1)
